<!-- 博客编辑或添加页面 -->
<template>
  <div>
    <!-- 顶部 -->
    <van-sticky>
      <div class="top_div">
        <div class="currentTime">{{ currentTime }}</div>
      </div>
    </van-sticky>
    <!-- 编辑或添加 -->
    <div class="edit_or_add_main">
      <div class="pad_main">
        <div class="cancel_publish">
          <van-button
            icon="https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/icon/cancel.png"
            size="small"
            color="#47EB9B"
            @click="cancel"
          >
            &nbsp;取 消&nbsp;
          </van-button>
          <van-button
            icon="https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/icon/publish.png"
            color="#47EB9B"
            size="small"
            @click="publish"
          >
            &nbsp;发 表&nbsp;
          </van-button>
        </div>

        <!-- 编辑框 -->
        <div class="edit_main">
          <textarea
            style="white-space: pre-wrap;"
            type="text"
            id="input_text"
            v-model="editContent"
            @input="calculateWords"
          ></textarea>
          <div class="blog_tag_words">
            <van-field
              v-model="blogTag"
              label="标签"
              placeholder="输入标签"
              label-width="3em"
            />
            <div class="words">{{ wordsNum }}&nbsp;字</div>
          </div>
        </div>
        <!-- 上传图片 -->
        <div class="upload_div">上传图片</div>
        <!-- 图片list -->
        <div
          class="blog_img_list"
          v-if="blogAid != -1 && imageEditList[0] != ''"
        >
          <div
            v-for="(item, index) in imageEditList"
            :key="index"
            class="image_del"
          >
            <van-image
              id="blog_img_per"
              width="5.5rem"
              height="5.5rem"
              radius="5px"
              fit="fill"
              :src="item"
              @click="clickPicEnlarge(imageEditList, index)"
            />
            <div class="del" @click="delPic(item)">
              <van-icon name="delete" color="#F56C6C" />
            </div>
          </div>
        </div>
        <van-uploader
          v-model="fileList"
          multiple
          :before-read="beforeRead"
          :after-read="afterRead"
          :deletable="false"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { ImagePreview } from 'vant'
import { client } from '../../utils/alioss'
import {
  addOrEditBlog,
  getBlogAllInfoByAid,
  deleteImage,
} from '../../api/blog'
import { getCurrentWeek } from '../../utils/tools.js'
export default {
  data() {
    return {
      blogAid: this.$route.query.blogAid, // 其他页面传过来的日记aid
      editContent: '',
      currentTime: '2022.7.1 15:52 周五',
      wordsNum: '0', // 日记的字数
      blogTag: '', // 日记标签
      fileList: [], // 上传图片后的list
      imagesList: [], // 上传到后端的list
      imageEditList: [], // 编辑的时候原来的图片
    }
  },
   created() {
    // 前端直接获取当前时间
    this.getCurrentTimeFunc()
    // 获取日记内容（如果是编辑）
    this.getBlogDetailFunc()
  },

  methods: {
    // 前端直接获取当前时间
    getCurrentTimeFunc() {
      let date = new Date()
      // 年
      let year = date.getFullYear().toString()
      // 月
      let month = Number(date.getMonth()) + 1
      // 日
      let day = date.getDate().toString()
      // 时
      let hour =
        date.getHours().toString().length === 1
          ? '0' + date.getHours().toString()
          : date.getHours().toString()
      // 分
      let minute =
        date.getMinutes().toString().length === 1
          ? '0' + date.getMinutes().toString()
          : date.getMinutes().toString()
      // 周几
      let week = getCurrentWeek()

      this.currentTime =
        year +
        '年' +
        month +
        '月' +
        day +
        '日' +
        ' ' +
        hour +
        ':' +
        minute +
        ' ' +
        week
    },

    // 获取日记内容（如果是编辑）
    getBlogDetailFunc() {
      let blogAid = this.$route.query.blogAid
      if (blogAid != -1) {
        getBlogAllInfoByAid(this.$route.query.blogAid).then((res) => {
          console.log(res)
          this.editContent = res.data.data.blogContent
          this.wordsNum = this.editContent.length
          this.blogTag = res.data.data.tags
          this.imageEditList = res.data.data.blogImageList
        })
      }
    },

    // 点击图片放大
    clickPicEnlarge(imageEditList, index) {
      ImagePreview({
        images: imageEditList,
        startPosition: index,
      })
    },

    // 输入框内容改变的时候计算字数
    calculateWords() {
      this.wordsNum = this.editContent.length
    },

    // 图片上传之前的判断
    beforeRead(file) {
      if (file.type === 'image/jpeg' || file.type === 'image/png') {
        return true
      } else {
        this.$toast('请上传 jpg 或 png 格式的图片')
        return false
      }
    },

    // 图片上传至阿里云
    afterRead(file) {
      // 定义唯一文件名
      var fileName = 'blog/' + `${Date.parse(new Date())}` + '.jpg'
      client()
        .multipartUpload(fileName, file.file)
        .then(() => {
          // this.$toast.success('上传成功！')
          let url =
            'https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/' + fileName
          this.imagesList.push(url)
        })
    },

    // 点击删除图标删除该图片
    delPic(url) {
      const params = {
        url: url,
        blogAid: this.blogAid,
      }
      deleteImage(params).then((res) => {
        if (res.data.code === 10000) {
          this.getBlogDetailFunc()
        }
      })
    },

    // 点击取消按钮
    cancel() {
      if (this.editContent === '' && this.imagesList.length === 0) {
        this.$router.back()
      } else {
        this.$dialog
          .confirm({
            message: '是否保存为草稿？',
          })
          .then(() => {
            // 确定保存为草稿
            let imageUrls = ''
            if (this.blogAid != -1) {
              for (const item of this.imageEditList) {
                imageUrls = imageUrls + item + ';'
              }
            }
            for (const item of this.imagesList) {
              imageUrls = imageUrls + item + ';'
            }
            imageUrls = imageUrls.substring(0, imageUrls.lastIndexOf(';'))
            const params = {
              blogAid: this.blogAid,
              content: this.editContent,
              tag: this.blogTag,
              imageUrls: imageUrls,
              published: 0, // 保存为草稿，未发表
            }
            addOrEditBlog(params).then((res) => {
              if (res.data.code === 10000) {
                this.$toast({
                  message: res.data.message,
                  duration: 800,
                  type: 'success',
                })
              }
              this.$router.back()
            })
          })
          .catch(() => {
            // 不保存草稿
            this.$router.back()
          })
      }
    },

    // 发表日记
    publish() {
      let imageUrls = ''
      if (this.blogAid != -1 && this.imageEditList[0] != '') {
        for (const item of this.imageEditList) {
          imageUrls = imageUrls + item + ';'
        }
      }

      for (const item of this.imagesList) {
        imageUrls = imageUrls + item + ';'
      }

      imageUrls = imageUrls.substring(0, imageUrls.lastIndexOf(';'))
      const params = {
        blogAid: this.blogAid,
        content: this.editContent,
        tag: this.blogTag,
        imageUrls: imageUrls,
        published: 1, // 发表
      }
      addOrEditBlog(params).then((res) => {
        if (res.data.code === 10000) {
          this.$toast({
            message: res.data.message,
            duration: 800,
            type: 'success',
          })
        }
        this.$router.back();
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.top_div {
  width: 100%;
  height: 2em;
  background-color: rgb(86, 82, 82);
  color: aliceblue;
  padding-top: 2em;
  text-align: center;
}

.currentTime {
  margin-right: 20px;
}
.edit_or_add_main {
  width: 100%;
  background-image: url('https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/diary/editDiaryPage_bg.png');
  background-size: cover;
  background-repeat: no-repeat;
  min-height: 90vh;
}
.cancel_publish {
  display: flex;
  justify-content: space-between;
}
.pad_main {
  width: 95%;
  margin: auto;
}
.van-button {
  margin-top: 10px;
  border-radius: 5px;
}
.edit_main {
  margin-top: 10px;
}
#input_text {
  width: 90%;
  height: auto;
  min-height: 200px;
  border: none;
  opacity: 0.7;
  margin-left: 12px;
  padding: 5px;
  color: #1e1e20;
  font-size: 17px;
  letter-spacing: 2px;
}
.blog_tag_words {
  width: 90%;
  display: flex;
  justify-content: space-between;
  margin-left: 12px;
}
.words {
  color: #909399;
}
/deep/ .van-field__label {
  color: #909399 !important;
}
/deep/ .van-cell {
  width: 80% !important;
  border-radius: 7px;
}
.van-uploader {
  margin-top: 15px;
  margin-left: 12px;
}
.upload_div {
  margin-top: 15px;
  margin-left: 12px;
  color: #909399;
}
.blog_img_list {
  width: 19em;
  display: flex;
  flex-flow: wrap;
  margin-left: 12px;
  margin-top: 10px;
}
.image_del {
  margin-right: 12px;
  margin-bottom: 15px;
}
.del {
  text-align: center;
}
</style>
